package com.org.manhu.chargehelper.ui.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.org.manhu.chargehelper.ChargeApplication;
import com.org.manhu.chargehelper.R;
import com.org.manhu.chargehelper.adapter.LogListAdapter;
import com.org.manhu.chargehelper.constant.Constant;
import com.org.manhu.chargehelper.custom.XListView;
import com.org.manhu.chargehelper.custom.XListView.IXListViewListener;
import com.org.manhu.chargehelper.tools.DeviceInfo;
import com.org.manhu.chargehelper.tools.JsonUtil;
import com.org.manhu.chargehelper.tools.NetUtils;
import com.org.manhu.chargehelper.tools.SharedPreferncesUtil;
import com.org.manhu.chargehelper.tools.ToastUtils;
import com.org.manhu.chargehelper.webservice.AsyncProcessData;

/**
 * @文件名：AwardLogFragment.java
 * @包名：com.org.manhu.chargehelper.ui.fragment
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年2月5日 下午9:10:49
 *
 * @描述：
 */
public class AwardLogFragment extends Fragment implements IXListViewListener {

	private View view;
	private XListView logList;
	private TextView noDataTipsTv;

	private LogListAdapter adapter;
	List<Map<String, String>> list = new ArrayList<Map<String, String>>();

	private AsyncProcessData request;

	private String channelId;
	private String devId;

	private int nowPage = 1;
	private int totalPage = -1;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			String json = msg.getData().getString("jsonStr");
			if (Constant.GET_AWARD_LOGS.equals(msg.obj.toString())) {
				onLoad();
				Log.d("TAG", "奖励记录：：：" + json);
				Map<String, String> feedbackMap = JsonUtil.parseAll(json);
				if (feedbackMap != null) {
					if (feedbackMap.get("Code").equals("0")) {
						clientInit();
					} else {
						parseListData(json);
					}
				} else {
					requestData();
				}
			} else if (Constant.CLIENT_INIT.equals(msg.obj.toString())) {
				Map<String, String> feedbackMap = JsonUtil.parseAll(json);
				if (feedbackMap != null) {
					ChargeApplication.updateInitInfo(feedbackMap);
					requestData();
				} else {
					clientInit();
				}
			}
		}

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		view = inflater.inflate(R.layout.fragment_log, null);
		logList = (XListView) view.findViewById(R.id.log_list);
		noDataTipsTv = (TextView) view
				.findViewById(R.id.log_fragment_no_data_tv);

		logList.setPullLoadEnable(false);
		adapter = new LogListAdapter(getActivity(), list,
				Constant.LOG_LIST_AWARD_FLAG);
		logList.setAdapter(adapter);
		logList.setXListViewListener(this);

		request = new AsyncProcessData();
		requestData();
		return view;
	}

	/**
	 * @描述：
	 * @param json
	 */
	private void parseListData(String json) {
		List<Map<String, String>> data = JsonUtil.parseToList(json);
		if (totalPage == -1) {
			totalPage = JsonUtil.getTotalPage(json);
		}
		if (totalPage > 1) {
			logList.setPullLoadEnable(true);
		}
		if (data != null) {
			logList.setVisibility(View.VISIBLE);
			if (data.size() == 0) {
				logList.setVisibility(View.GONE);
				noDataTipsTv.setText("暂无数据");
			}
			if (nowPage == 1) {
				adapter.clearData();
			}
			adapter.setData(data);
			adapter.notifyDataSetChanged();
		}
	};

	/**
	 * @描述： 客户端初始化，获取AuthKey
	 */
	private void clientInit() {
		if (NetUtils.isConnected(getActivity())) {
			if (Constant.IS_USE_BOXINFO) {
				channelId = SharedPreferncesUtil.getBoxInfo(getActivity(),
						Constant.SP_BOX_CHANNELID);
				devId = SharedPreferncesUtil.getBoxInfo(getActivity(),
						Constant.SP_BOX_DEVID);
			} else {
				channelId = "0";
				devId = "0";
			}
			request.getRequestData(mHandler, Constant.CLIENT_INIT, "AuthKey",
					"", "Imei", DeviceInfo.getIMEI(), "Imsi",
					DeviceInfo.getIMSI(), "AndroidId",
					DeviceInfo.getAndroidID(), "PhoneTypeId",
					DeviceInfo.getDeviceModel(), "ChannelId", channelId,
					"DevId", devId);
		} else {
			ToastUtils.showShort(getActivity(), "网络异常，请稍检查网络");
		}
	}

	/**
	 * @描述：
	 */
	private void requestData() {
		if (NetUtils.isConnected(getActivity())) {
			request.getRequestData(mHandler, Constant.GET_AWARD_LOGS,
					"AuthKey", ChargeApplication.getInitInfo().get("AuthKey"),
					"activeid", "0", "typeid", "1", "pageindex", "" + nowPage,
					"pagesize", "" + Constant.PAGE_SIZE);
		} else {
			if (list.size() == 0) {
				logList.setVisibility(View.GONE);
				noDataTipsTv.setText("请连接网络获取数据");
			}
		}
	}

	private void onLoad() {
		logList.stopLoadMore();
		logList.stopRefresh();
		logList.setRefreshTime("刚刚");
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		nowPage = 1;
		requestData();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		nowPage += 1;
		if (nowPage >= totalPage) {
			onLoad();
			ToastUtils.showShort(getActivity(), "已经没有更多数据了");
			logList.setPullLoadEnable(false);
			return;
		}
		requestData();
	}

}
